<template>
  <div>
    <div :id="id" :class="className" :style="{height:height+'px',width:width}" />
    <div :id="`${id}1`" :style="{height:(height+40)+'px',width:width}" />
  </div>
</template>

<script>
import * as echarts from 'echarts'
import resize from '../mixins/resize'
import { mapGetters } from 'vuex'
import { getNetWorthByInvestId, getFitNetWorthValue } from '@/api/afterInvest'
import { findIndexByIndexTypeAndIndexTime } from '@/api/policyManage'
import { upFixed, downFixed } from '@/utils'

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    id: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '200px'
    },
    height: {
      type: Number,
      default: 200
    },
    ids: {
      type: String | Number,
      required: true
    },
    id_index: {
      type: Array,
      default: () => {
        return []
      }
    },
    contrastOptions_obj: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      chart: null,
      startTime: '',
      endTime: '',
      xDate: [], // y轴
      fitNetWorth_obj: {}, // 拟合
      netWorth_obj: {}, // 净值
      contrastIndex_obj: {}, // 指数
    }
  },
  computed: {
    ...mapGetters(['index_dict'])
  },
  watch: {
    ids: {
      handler(id) {
        if(id) {
          Promise.all([this.getFitNetWorthValue(id), this.getNetWorthByInvestId(id)]).then(res => {
            console.log('曲线:', res)
            this.startTime = res[0][0].networthTime
            this.endTime = res[0][res[0].length-1].networthTime
            this.fitNetWorth_obj['拟合'] = []
            res[0].forEach(item => {
              // this.xDate.push(item.networthTime)
              this.fitNetWorth_obj['拟合'].push(item.networthValue)
            })
            res[1].body.forEach(items => {
              this.xDate.push(items.date)
              // const key = Object.keys(items)[0]
              // this.netWorth_obj[key] = items[key]&&Array.isArray(items[key])&&items[key].map(item => item.networthValue) || []
              items.item.map(element => {
                if(!this.netWorth_obj[element.key]) this.netWorth_obj[element.key] = []
                this.netWorth_obj[element.key].push(element.netWorth)
              })
            })
            this.$nextTick(() => {
              this.chart && this.chart.dispose()
              this.initChart(this.fitNetWorth_obj, this.netWorth_obj)
            })
          })
        }
      },
      deep: true,
      immediate: true
    },
    id_index: {
      handler(id) {
        if(this.startTime&&this.endTime) {
          this.findIndexByIndexTypeAndIndexTime(this.startTime, this.endTime, id)
        }else {
          setTimeout(() => {
            this.findIndexByIndexTypeAndIndexTime(this.startTime, this.endTime, id)
          }, 1000)
        }
      },
      deep: true,
      immediate: true
    }
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart(obj1, obj2) {
      this.chart = echarts.init(document.getElementById(this.id))
      this.chart1 = echarts.init(document.getElementById(this.id+'1'))

      const color_list = [
        'rgba(225,103,86,1)', 'rgba(129,183,236,1)', 'rgba(238,203,87,1)', 'rgba(173,224,255,1)', 'rgba(255,155,203,1)',
        '#fff143','#bce672','#f36838','#70f3ff','#d9b611','#96ce54','#ff4777','#44cef6','#eedeb0','#0aa344','#f00056','#4b5cc4','#e29c45',
        '#21a675','#f9906f','#1685a9','#ae7000','#057748','#f05654','#a1afc9','#a78e44','#00e500','#c93756','#065279','#9b4400','#00e09e',
        '#8c4356','#3b2e7e','#7fecad','#f20c00','#426666','#827100','#a4e2c6','#9d2933','#815476','#6e511e','#0eb83a','#b36d61','#edd1d8',
        '#48c0a3','#bf242a','#4c221b','#549688','#60281e','#003371','#789262','#ff7500','#801dae','#758a99','#ffa631','#4c8dae','#50616d','#b0a4e3','#424c50','#cca4e3',
      ]
      const series_obj1 = []
      const series_obj2 = []

      if(Object.keys(obj1).length) {
        Object.keys(obj1).forEach((key, i) => {
          const item = obj1[key]
          series_obj1.push({
            name: key,
            type: 'line',
            symbolSize: 2,
            symbol: 'emptyCircle',
            showSymbol: false,
            lineStyle: {
              width: 1.6
            },
            itemStyle: {
              color: color_list[i]
            },
            data: item
          })
        })
      }

      if(Object.keys(obj2).length) {
        Object.keys(obj2).forEach((key, i) => {
          const item = obj2[key]
          // const data = item&&Array.isArray(item)&&item.map(item => item.networthValue) || []
          series_obj2.push({
            name: key,
            type: 'line',
            symbolSize: 2,
            symbol: 'emptyCircle',
            showSymbol: false,
            lineStyle: {
              width: 1.6
            },
            itemStyle: {
              color: color_list[i]
            },
            data: item
          })
        })
      }

      this.chart.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            textStyle: {
              color: '#fff'
            }
          },
          formatter(params) {
            let str = ''
            str += `<div style="padding-bottom: 2px;">${params[0].name}</div>`
            for (let i = 0; i < params.length; i += 1) {
              if(params[i].data!=null) {
                str += `<div style="display: flex;align-items: center;">
                      ${params[i].marker} 
                      <span style="flex:1;">${params[i].seriesName}</span> 
                      <span style="margin-left: 10px;font-weight: bold;"> ${params[i].data}%</span>
                      </div>`
              }
            }
            return str
          }
        },
        grid: {
          top: '15%',
          left: '7%',
          right: '5%',
          bottom: '10%',
          borderWidth: 0,
          textStyle: {
            color: '#fff'
          }
        },
        legend: {
          x: '6%',
          top: '2%',
          textStyle: {
            color: '#90979c'
          },
        },
        calculable: true,
        xAxis: [{
          type: 'category',
          boundaryGap: false, // 折线从x轴起始开始走
          splitNumber: 8,
          axisLine: {
            lineStyle: {
              color: '#90979c'
            }
          },
          splitLine: {
            show: false
          },
          axisTick: {
            show: true,
            alignWithLabel: true,
            interval: 'auto'
          },
          splitArea: {
            show: false
          },
          axisLabel: {
            interval: 'auto'
          },
          data: this.xDate,
        }],
        yAxis: [
          {
            type: 'value',
            min: function(value) {
              const num = value.min - (value.max - value.min)/5
              return downFixed(num, 1)
            },
            max: function(value) {
              const num = value.max + (value.max - value.min)/5
              return upFixed(num, 1)
            },
            splitNumber: 5,
            splitLine: {
              show: true,
              lineStyle: {
                type: 'dashed'
              }
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#90979c'
              }
            },
            axisTick: {
              show: true,
              alignWithLabel: true
            },
            axisLabel: {
              interval: 0,
              formatter: function(value) {
                return value.toFixed(4)
              }
            },
            splitArea: {
              show: false
            }
          }
        ],
        dataZoom: [{
          show: false,
          type: 'slider',
          start: 0,
          end: 100,
          realtime: true,
          height: '0%',
          bottom: '18%',
        }, {
          show: false,
          realtime: true, // 实时更新系列的视图
          height: '5%',
          bottom: '5%',
        }],
        series: series_obj1
      })
    
      this.chart1.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            textStyle: {
              color: '#fff'
            }
          },
          formatter(params) {
            let str = ''
            str += `<div style="padding-bottom: 2px;">${params[0].name}</div>`
            for (let i = 0; i < params.length; i += 1) {
              if(params[i].data!=null) {
                str += `<div style="display: flex;align-items: center;">
                      ${params[i].marker} 
                      <span style="flex:1;">${params[i].seriesName}</span> 
                      <span style="margin-left: 10px;font-weight: bold;"> ${params[i].data}%</span>
                      </div>`
              }
            }
            return str
          }
        },
        grid: {
          top: '15%',
          left: '7%',
          right: '5%',
          bottom: '20%',
          borderWidth: 0,
          textStyle: {
            color: '#fff'
          }
        },
        legend: {
          width: '88%',
          type: 'scroll',
          x: '6%',
          top: '2%',
          textStyle: {
            color: '#90979c'
          },
        },
        calculable: true,
        xAxis: [{
          type: 'category',
          boundaryGap: false, // 折线从x轴起始开始走
          splitNumber: 8,
          axisLine: {
            lineStyle: {
              color: '#90979c'
            }
          },
          splitLine: {
            show: false
          },
          axisTick: {
            show: true,
            alignWithLabel: true,
            interval: 'auto'
          },
          splitArea: {
            show: false
          },
          axisLabel: {
            interval: 'auto'
          },
          data: this.xDate,
        }],
        yAxis: [
          {
            type: 'value',
            min: function(value) {
              const num = value.min - (value.max - value.min)/5
              return downFixed(num, 1)
            },
            max: function(value) {
              const num = value.max + (value.max - value.min)/5
              return upFixed(num, 1)
            },
            splitNumber: 5,
            splitLine: {
              show: true,
              lineStyle: {
                type: 'dashed'
              }
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#90979c'
              }
            },
            axisTick: {
              show: true,
              alignWithLabel: true
            },
            axisLabel: {
              interval: 0,
              formatter: function(value) {
                return value.toFixed(4)
              }
            },
            splitArea: {
              show: false
            }
          }
        ],
        dataZoom: [{
          show: false,
          type: 'slider',
          start: 0,
          end: 100,
          realtime: true,
          height: '0%',
          bottom: '18%',
        }, {
          realtime: true, // 实时更新系列的视图
          height: '5%',
          bottom: '5%',
        }],
        series: series_obj2
      })
    
      this.chart1.on('datazoom', () => {
        const op = this.chart.getOption()
        const op1 = this.chart1.getOption()
        op.dataZoom[0].start = op1.dataZoom[0].start
        op.dataZoom[0].end = op1.dataZoom[0].end
        op.dataZoom[1].start = op1.dataZoom[1].start
        op.dataZoom[1].end = op1.dataZoom[1].end
        this.chart.setOption(op)
        this.chart1.setOption(op1)
      })
    },
    getNetWorthByInvestId(investId) {
      return new Promise(resolve => {
        getNetWorthByInvestId({
          investId
        }).then(res => {
          console.log('投后净值:', res)
          resolve(res)
        })
      })
    },
    getFitNetWorthValue(investId) {
      return new Promise(resolve => {
        getFitNetWorthValue({
          investId
        }).then(res => {
          console.log('拟合净值:', res)
          resolve(res)
        })
      })
    },
    // 指数走势
    findIndexByIndexTypeAndIndexTime(startTime, endTime, indexType) {
      findIndexByIndexTypeAndIndexTime({
        startTime,
        endTime,
        indexType
      }).then(res => {
        console.log('获取对比指标历史收益走势', res)
        this.contrastIndex_obj = {}
        Object.keys(res.body).forEach(key => {
          const item = res.body[key]
          const _key = this.contrastOptions_obj[key]
          // this.contrastIndex_obj[_key] = item
          this.contrastIndex_obj[_key] = item&&Array.isArray(item)&&item.map(item => item.indexValue) || []
        })
        this.fitNetWorth_obj = {
          ...this.fitNetWorth_obj,
          ...this.contrastIndex_obj
        }
        this.netWorth_obj = {
          ...this.netWorth_obj,
          ...this.contrastIndex_obj
        }
        this.$nextTick(() => {
          this.chart && this.chart.dispose()
          this.initChart(this.fitNetWorth_obj, this.netWorth_obj)
        })
      })
    }
  }
}
</script>
